package com.example.mangroves.controller;

import com.example.mangroves.entity.GeoDetails;
import com.example.mangroves.entity.GeoInfo;
import com.example.mangroves.entity.Phenology;
import com.example.mangroves.service.PhenologyService;
import com.example.mangroves.service.impl.GeoDetailServiceImpl;
import com.example.mangroves.service.impl.GeoInfoServiceImpl;
import com.example.mangroves.service.impl.PhenologyServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.awt.geom.GeneralPath;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@RestController
public class DataController {

    /**
     * 气象数据查询接口
     * 模拟CR6数据采集器的数据查询协议
     */
    @GetMapping("/data-query")
    public String fetchData(
            @RequestParam String command,
            @RequestParam("mode") String mode,
            @RequestParam("format") String format,
            @RequestParam("uri") String uri,
            @RequestParam("p1") int p1) {

        // 根据接收到的参数模拟返回数据
        if ("DataQuery".equals(command) && "most-recent".equals(mode) && "json".equals(format) && "dl:IRR".equals(uri) && p1 == 5) {
            return "{\"head\":{\"transaction\":0,\"signature\":62964,\"environment\":{\"station_name\":\"19902\",\"table_name\":\"Public\",\"model\":\"CR6\",\"serial_no\":\"19902\",\"os_version\":\"CR6.Std.12.02\",\"prog_name\":\"CPU:DJSH20231214-LB1_EasyFlux_DL_CR6OP_v2_01.cr6\"},\"fields\":[{\"name\":\"message\",\"type\":\"xsd:string\",\"settable\":true,\"string_len\":64},{\"name\":\"card_storage_available_days\",\"type\":\"xsd:float\",\"units\":\"days\",\"settable\":true},{\"name\":\"sonic_azimuth\",\"type\":\"xsd:float\",\"units\":\"Decimal degrees\",\"settable\":true},{\"name\":\"latitude\",\"type\":\"xsd:float\",\"units\":\"Decimal degrees\",\"settable\":true},{\"name\":\"hemisphere_NS\",\"type\":\"xsd:float\",\"units\":\"adimensional\",\"settable\":true},{\"name\":\"longitude\",\"type\":\"xsd:float\",\"units\":\"Decimal degrees\",\"settable\":true},{\"name\":\"hemisphere_EW\",\"type\":\"xsd:float\",\"units\":\"adimensional\",\"settable\":true},{\"name\":\"altitude\",\"type\":\"xsd:float\",\"units\":\"m\",\"settable\":true},{\"name\":\"height_measurement\",\"type\":\"xsd:float\",\"units\":\"m\",\"settable\":true},{\"name\":\"surface_type\",\"type\":\"xsd:float\",\"units\":\"adimensional\",\"settable\":true},{\"name\":\"height_canopy\",\"type\":\"xsd:float\",\"units\":\"m\",\"settable\":true},{\"name\":\"displacement_user\",\"type\":\"xsd:float\",\"units\":\"m\",\"settable\":true},{\"name\":\"roughness_user\",\"type\":\"xsd:float\",\"units\":\"m\",\"settable\":true},{\"name\":\"separation_x_irga\",\"type\":\"xsd:float\",\"units\":\"m\",\"settable\":true},{\"name\":\"separation_y_irga\",\"type\":\"xsd:float\",\"units\":\"m\",\"settable\":true},{\"name\":\"dist_intrst_60_300\",\"type\":\"xsd:float\",\"units\":\"m\",\"settable\":true},{\"name\":\"dist_intrst_60_170\",\"type\":\"xsd:float\",\"units\":\"m\",\"settable\":true},{\"name\":\"dist_intrst_170_190\",\"type\":\"xsd:float\",\"units\":\"m\",\"settable\":true},{\"name\":\"dist_intrst_190_300\",\"type\":\"xsd:float\",\"units\":\"m\",\"settable\":true},{\"name\":\"T_panel\",\"type\":\"xsd:float\",\"units\":\"deg C\",\"settable\":true},{\"name\":\"V_batt\",\"type\":\"xsd:float\",\"units\":\"V\",\"settable\":true},{\"name\":\"alpha_PF_60_300\",\"type\":\"xsd:float\",\"units\":\"Decimal degrees\",\"settable\":true},{\"name\":\"beta_PF_60_300\",\"type\":\"xsd:float\",\"units\":\"Decimal degrees\",\"settable\":true},{\"name\":\"alpha_PF_60_170\",\"type\":\"xsd:float\",\"units\":\"Decimal degrees\",\"settable\":true},{\"name\":\"beta_PF_60_170\",\"type\":\"xsd:float\",\"units\":\"Decimal degrees\",\"settable\":true},{\"name\":\"alpha_PF_170_190\",\"type\":\"xsd:float\",\"units\":\"Decimal degrees\",\"settable\":true},{\"name\":\"beta_PF_170_190\",\"type\":\"xsd:float\",\"units\":\"Decimal degrees\",\"settable\":true},{\"name\":\"alpha_PF_190_300\",\"type\":\"xsd:float\",\"units\":\"Decimal degrees\",\"settable\":true},{\"name\":\"beta_PF_190_300\",\"type\":\"xsd:float\",\"units\":\"Decimal degrees\",\"settable\":true},{\"name\":\"Planar_Fit_flg\",\"type\":\"xsd:boolean\",\"settable\":true},{\"name\":\"d\",\"type\":\"xsd:float\",\"units\":\"m\",\"settable\":true},{\"name\":\"z0\",\"type\":\"xsd:float\",\"units\":\"m\",\"settable\":true},{\"name\":\"z\",\"type\":\"xsd:float\",\"units\":\"m\",\"settable\":true},{\"name\":\"press_source\",\"type\":\"xsd:float\",\"settable\":true},{\"name\":\"heater_actual\",\"type\":\"xsd:float\",\"settable\":true},{\"name\":\"heater_user\",\"type\":\"xsd:float\",\"settable\":true},{\"name\":\"irga_power\",\"type\":\"xsd:float\",\"settable\":true},{\"name\":\"select_CO2_fast_tmpr\",\"type\":\"xsd:boolean\",\"settable\":true},{\"name\":\"shadow_corr\",\"type\":\"xsd:float\",\"settable\":true},{\"name\":\"CO2_span_gas\",\"type\":\"xsd:float\",\"units\":\"umol mol-1\",\"settable\":true},{\"name\":\"T_DP_span_gas\",\"type\":\"xsd:float\",\"units\":\"deg C\",\"settable\":true},{\"name\":\"CO2_zero_coeff\",\"type\":\"xsd:float\",\"settable\":true},{\"name\":\"CO2_span_coeff\",\"type\":\"xsd:float\",\"settable\":true},{\"name\":\"H2O_zero_coeff\",\"type\":\"xsd:float\",\"settable\":true},{\"name\":\"H2O_span_coeff\",\"type\":\"xsd:float\",\"settable\":true},{\"name\":\"set_press_source_flg\",\"type\":\"xsd:boolean\",\"settable\":true},{\"name\":\"set_zero_flg\",\"type\":\"xsd:boolean\",\"settable\":true},{\"name\":\"set_CO2_span_flg\",\"type\":\"xsd:boolean\",\"settable\":true},{\"name\":\"set_H2O_span_flg\",\"type\":\"xsd:boolean\",\"settable\":true},{\"name\":\"set_heater_flg\",\"type\":\"xsd:boolean\",\"settable\":true},{\"name\":\"set_irga_power_flg\",\"type\":\"xsd:boolean\",\"settable\":true},{\"name\":\"set_CO2_fast_tmpr_flg\",\"type\":\"xsd:boolean\",\"settable\":true},{\"name\":\"set_shadow_corr_flg\",\"type\":\"xsd:boolean\",\"settable\":true},{\"name\":\"rst_CO2_zro_coef_flg\",\"type\":\"xsd:boolean\",\"settable\":true},{\"name\":\"rst_CO2_spn_coef_flg\",\"type\":\"xsd:boolean\",\"settable\":true},{\"name\":\"rst_H2O_zro_coef_flg\",\"type\":\"xsd:boolean\",\"settable\":true},{\"name\":\"rst_H2O_spn_coef_flg\",\"type\":\"xsd:boolean\",\"settable\":true},{\"name\":\"irga_vlt_low_auto_off\",\"type\":\"xsd:boolean\",\"settable\":true},{\"name\":\"irga_actual_pwr_on\",\"type\":\"xsd:boolean\",\"settable\":true},{\"name\":\"irga_user_set_pwr_on\",\"type\":\"xsd:boolean\",\"settable\":true},{\"name\":\"secs_snc_pwr_swtch\",\"type\":\"xsd:float\",\"settable\":true},{\"name\":\"Ts\",\"type\":\"xsd:float\",\"units\":\"deg C\",\"settable\":true},{\"name\":\"Ux\",\"type\":\"xsd:float\",\"units\":\"m s-1\",\"settable\":true},{\"name\":\"Uy\",\"type\":\"xsd:float\",\"units\":\"m s-1\",\"settable\":true},{\"name\":\"Uz\",\"type\":\"xsd:float\",\"units\":\"m s-1\",\"settable\":true},{\"name\":\"diag_sonic\",\"type\":\"xsd:float\",\"units\":\"adimensional\",\"settable\":true},{\"name\":\"FP_DIST_INTRST\",\"type\":\"xsd:float\",\"units\":\"%\",\"settable\":true},{\"name\":\"CO2_density\",\"type\":\"xsd:float\",\"units\":\"mg m-3\",\"settable\":true},{\"name\":\"H2O_density\",\"type\":\"xsd:float\",\"units\":\"g m-3\",\"settable\":true},{\"name\":\"diag_irga\",\"type\":\"xsd:float\",\"units\":\"adimensional\",\"settable\":true},{\"name\":\"T_amb\",\"type\":\"xsd:float\",\"units\":\"deg C\",\"settable\":true},{\"name\":\"press_amb\",\"type\":\"xsd:float\",\"units\":\"kPa\",\"settable\":true},{\"name\":\"CO2_sig_strgth\",\"type\":\"xsd:float\",\"units\":\"fraction\",\"settable\":true},{\"name\":\"H2O_sig_strgth\",\"type\":\"xsd:float\",\"units\":\"fraction\",\"settable\":true},{\"name\":\"RH_amb\",\"type\":\"xsd:float\",\"units\":\"%\",\"settable\":true},{\"name\":\"T_DP_amb\",\"type\":\"xsd:float\",\"units\":\"deg C\",\"settable\":true},{\"name\":\"e_sat_amb\",\"type\":\"xsd:float\",\"units\":\"kPa\",\"settable\":true},{\"name\":\"e_amb\",\"type\":\"xsd:float\",\"units\":\"kPa\",\"settable\":true},{\"name\":\"rho_d_amb\",\"type\":\"xsd:float\",\"units\":\"g m-3\",\"settable\":true},{\"name\":\"rho_a_amb\",\"type\":\"xsd:float\",\"units\":\"kg m-3\",\"settable\":true},{\"name\":\"Tc\",\"type\":\"xsd:float\",\"units\":\"deg C\",\"settable\":true},{\"name\":\"RH\",\"type\":\"xsd:float\",\"units\":\"%\",\"settable\":true},{\"name\":\"T_DP\",\"type\":\"xsd:float\",\"units\":\"deg C\",\"settable\":true},{\"name\":\"e_sat\",\"type\":\"xsd:float\",\"units\":\"kPa\",\"settable\":true},{\"name\":\"e\",\"type\":\"xsd:float\",\"units\":\"kPa\",\"settable\":true},{\"name\":\"rho_d\",\"type\":\"xsd:float\",\"units\":\"g m-3\",\"settable\":true},{\"name\":\"rho_a\",\"type\":\"xsd:float\",\"units\":\"kg m-3\",\"settable\":true},{\"name\":\"CO2_mixratio\",\"type\":\"xsd:float\",\"units\":\"umol/mol\",\"settable\":true},{\"name\":\"H2O_mixratio\",\"type\":\"xsd:float\",\"units\":\"mmol/mol\",\"settable\":true}]},\"data\":[{\"time\":\"2024-06-07T21:18:50.271\",\"no\":110305,\"vals\":[\"H2Ospn coef in rng.\",1940.24,210,22.5923,1,113.978,-1,30,2.5,2,1.3,0,0,0,0,159.3119,159.3119,159.3119,159.3119,28.39334,11.37594,0,0,0,0,0,0,0,0,false,0.9068814,0.1691697,1.593119,0,-1,-1,0,true,0,420,20,1.000444,1.007158,1.000375,1.011267,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,11030,27.96196,0.1594612,-0.06233347,0.04917537,0,96.99618,824.8263,22.66737,0,24.92245,101.0034,0.8266846,0.8137168,98.46982,24.66416,3.166556,3.118102,1144.243,1.166911,24.99374,98.07559,24.66817,3.180044,3.118847,1143.961,1.166628,474.6232,31.85548]}]}";
        } else {
            return "{\"error\": \"Invalid parameters\"}";
        }
    }

    /**
     * 随机数据生成接口
     * 用于前端测试和功能演示
     */
    @GetMapping("/random-data")
    public Map<String, Object> getRandomData() {
        Map<String, Object> data = new HashMap<>();
        data.put("value", Math.random() * 100); // 生成随机数
        return data;
    }

    // 随机数生成器实例
    private final Random random = new Random();

    /**
     * 随机JSON数据生成接口
     * 生成包含随机传感器数据的模拟设备响应
     */
    @GetMapping("/random-jsondata")
    public String getRandomJsonData() {
        // 生成随机的签名和一些随机的传感器数据
        int signature = random.nextInt(100000);
        double sonicAzimuth = 360 * random.nextDouble();    // 声波方位角
        double latitude = -90 + 180 * random.nextDouble();  // 纬度坐标
        double longitude = -180 + 360 * random.nextDouble(); // 经度坐标

        return String.format("{\"head\":{\"transaction\":0,\"signature\":%d,\"environment\":{\"station_name\":\"19902\",\"table_name\":\"Public\",\"model\":\"CR6\",\"serial_no\":\"19902\",\"os_version\":\"CR6.Std.12.02\",\"prog_name\":\"CPU:DJSH20231214-LB1_EasyFlux_DL_CR6OP_v2_01.cr6\"},\"fields\":[{\"name\":\"message\",\"type\":\"xsd:string\",\"settable\":true,\"string_len\":64},{\"name\":\"sonic_azimuth\",\"type\":\"xsd:float\",\"units\":\"Decimal degrees\",\"settable\":true,\"value\":%.2f},{\"name\":\"latitude\",\"type\":\"xsd:float\",\"units\":\"Decimal degrees\",\"settable\":true,\"value\":%.2f},{\"name\":\"longitude\",\"type\":\"xsd:float\",\"units\":\"Decimal degrees\",\"settable\":true,\"value\":%.2f}]},\"data\":[{\"time\":\"2024-06-07T21:18:50.271\",\"no\":110305,\"vals\":[\"H2Ospn coef in rng.\",1940.24,210,22.5923,1,113.978,-1,30,2.5,2,1.3,0,0,0,0,159.3119,159.3119,159.3119,159.3119,28.39334,11.37594,0,0,0,0,0,0,0,0,false,0.9068814,0.1691697,1.593119,0,-1,-1,0,true,0,420,20,1.000444,1.007158,1.000375,1.011267,false,false,false,false,false,false,false,false,false,false,false,false,false,true,true,11030,27.96196,0.1594612,-0.06233347,0.04917537,0,96.99618,824.8263,22.66737,0,24.92245,101.0034,0.8266846,0.8137168,98.46982,24.66416,3.166556,3.118102,1144.243,1.166911,24.99374,98.07559,24.66817,3.180044,3.118847,1143.961,1.166628,474.6232,31.85548]}]}",
                signature, sonicAzimuth, latitude, longitude);
    }

    @Autowired
    GeoInfoServiceImpl geoInfoServiceImpl;

    @Autowired
    GeoDetailServiceImpl geoDetailServiceImpl;

    /**
     * 核心气象指标数据查询接口
     * 从数据库获取最新地理信息并返回关键气象指标
     * 包含模拟数据生成用于演示环境
     */
    @GetMapping("/getdata")
    public String getData() {
        // 查询最新的地理信息记录
        GeoInfo geoInfo = geoInfoServiceImpl.getLastGeoInfo();
        if (geoInfo == null) {
            return "{}"; // 无数据时返回空JSON对象
        }

        List<GeoDetails> geoDetails = geoDetailServiceImpl.getGeoDetailsByGeoInfoId(geoInfo.getId());
        if (geoDetails == null || geoDetails.isEmpty()) {
            return "{}"; // 无详情数据时返回空JSON对象
        }

        // 初始化指标值
        double latitude = 0.0;
        double longitude = 0.0;
        double ux = 0.0;
        double uy = 0.0;
        double co2Density = 0.0;
        double h2oDensity = 0.0;
        double tPanel = 0.0;
        double battVolt = 0.0;

        // 遍历geoDetails以找到相应的指标值
        for (GeoDetails detail : geoDetails) {
            switch (detail.getName()) {
                case "latitude":
                    latitude = Double.parseDouble(detail.getValue());
                    break;
                case "longitude":
                    longitude = Double.parseDouble(detail.getValue());
                    break;
                case "Ux":
                    ux = Double.parseDouble(detail.getValue());
                    break;
                case "Uy":
                    uy = Double.parseDouble(detail.getValue());
                    break;
                case "CO2_density":
                    co2Density = Double.parseDouble(detail.getValue());
                    break;
                case "H2O_density":
                    h2oDensity = Double.parseDouble(detail.getValue());
                    break;
                case "T_panel":
                    tPanel = Double.parseDouble(detail.getValue());
                    break;
                case "V_batt":
                    battVolt = Double.parseDouble(detail.getValue());
                    break;
            }
        }
        // 模拟数据生成（演示环境使用）
        latitude = 22.5726 + random.nextDouble() * 0.01 - 0.005;   // 纬度在小范围内随机波动
        longitude = 88.3639 + random.nextDouble() * 0.01 - 0.005;  // 经度在小范围内随机波动
        ux = random.nextDouble() * 10;         // X轴风速模拟
        uy = random.nextDouble() * 10;         // Y轴风速模拟
        co2Density = random.nextDouble() * 1000; // 二氧化碳密度模拟
        h2oDensity = random.nextDouble() * 50;   // 水汽密度模拟
        tPanel = 20 + random.nextDouble() * 10;  // 面板温度模拟
        battVolt = 12 + random.nextDouble();     // 电池电压模拟

        // 构造JSON字符串并返回
        return String.format("{\"latitude\":%.2f,\"longitude\":%.2f,\"Ux\":%.2f,\"Uy\":%.2f,\"CO2_density\":%.2f,\"H2O_density\":%.2f,\"T_panel\":%.2f,\"batt_volt\":%.2f}",
                latitude, longitude, ux, uy, co2Density, h2oDensity, tPanel, battVolt);
    }

    @Autowired
    private PhenologyServiceImpl phenologyServiceImpl;

    /**
     * 物候数据查询接口
     * 返回所有物候观测记录数据
     */
    @GetMapping("/phenology-data")
    public ResponseEntity<List<Phenology>> getAllPhenologyData() {
        List<Phenology> data = phenologyServiceImpl.getAllPhenology();
        System.out.println("******&&&&&&&&&&&&&&&&&&&&&&&&&"+data);
        return ResponseEntity.ok(data);
    }

}

